<?php

namespace app\merchant\controller;

use think\Controller;
use app\common\model\Merchant as MerchantModel;
use app\common\controller\Tools;
use think\captcha\Captcha;
use app\common\model\TempPhone;
use think\Db;
use think\Request;

class Index extends Controller
{
    public $captcha;
    public $tempPhone;

    public function __construct(Request $request,Captcha $captcha,TempPhone $tempPhone)
    {
        parent::__construct($request);
        $this->captcha = $captcha;
        $this->tempPhone = $tempPhone;
    }

    public function login()
    {
        if (session('merchant')) {
            if (session('merchant.merchant_account_status') == 1) {
                $this->redirect('home/index');
            } elseif (session('merchant.merchant_account_status') == 2) {
                //企业认证，店铺认证判断
                $enterpriseStatus = Db::name('enterprise')
                    ->where('enterprise_merchant_id', session('merchant.merchant_id'))
                    ->where('enterprise_is_delete', 0)
                    ->value('enterprise_verify_status');
                $storeStatus = Db::name('store')
                    ->where('store_merchant_id', session('merchant.merchant_id'))
                    ->where('store_is_delete', 0)
                    ->value('store_verify_status');
                if ($enterpriseStatus == 0) {
                    $this->redirect('enterprise/create');
                } else if ($enterpriseStatus == 1) {
                    if ($storeStatus == 0) {
                        $this->redirect('store/create');
                    } else {
                        $this->redirect('enterprise/confirm');
                    }
                } else if ($enterpriseStatus == 2) {
                    if ($storeStatus == 2) {
                        $this->redirect('index/active');
                    } else {
                        $this->redirect('enterprise/confirm');
                    }
                }
            }
        }
        return view('login');
    }

    public function active()
    {
        return view('active');
    }


    public function agreement()
    {
        return view('agreement');
    }

    // 获取验证码
    public function captcha()
    {
        return MerchantModel::makeCaptcha();
    }

    //登录
    public function loginDo()
    {
        if (request()->isAjax()) {
            $tel = input('param.tel');
            $pw = input('param.pw');
            $code = input('param.captcha');
            if (empty($tel) || empty($pw))
                return returnJson(0, '手机号或密码不能为空');
            if (empty($code))
                return returnJson(0, '验证码不能为空');
            $is_mobile = is_mobile($tel);
            if (!$is_mobile)
                return returnJson(0, '请输入正确手机号');

            $captcha = new \think\captcha\Captcha();
            if (!$captcha->check($code)) {
                return returnJson(0, '验证码错误');
            }

            $merchant = MerchantModel::getMerchant($tel);
            if (!$merchant)
                return returnJson(0, '该手机号尚未注册');

            if($merchant['merchant_account_status'] == 3)
                return returnJson(0, '账户异常');

            if ($merchant['merchant_password'] !== encryption_pwd($pw))
                return returnJson(0, '手机号与密码不符');


            cookie('phone', $merchant['merchant_tel'], time() + 3 * 3600);
            session('merchant', $merchant);

            $data['merchant_account_status'] = session('merchant.merchant_account_status');
            $checkStatus = MerchantModel::checkStatus();
            $data['store_verify_status'] = $checkStatus['store_verify_status'] ?: 0;
            $data['store_id'] = $checkStatus['store_id'] ?: 0;
            $data['enterprise_id'] = $checkStatus['enterprise_id'] ?: 0;
            $data['enterprise_verify_status'] = $checkStatus['enterprise_verify_status'] ?: 0;
            return returnJson(1, '登录成功', $data);
        } else {
            return returnJson(0, '请使用正确的方式提交数据');
        }
    }

    public function register()
    {
        return view('register');
    }

    public function registerDo()
    {
        if (request()->isAjax()) {
            $tel = input('param.tel');
            $pw = input('param.pw');
            $phone_code = input('param.phone_code');
            if (empty($tel) || empty($pw))
                return returnJson(0, '手机号或密码不能为空');
            $is_mobile = is_mobile($tel);
            if (!$is_mobile)
                return returnJson(0, '请输入正确手机号');
            $hasMobile = MerchantModel::getMerchant($tel);
            if ($hasMobile)
                return returnJson(0, '该手机号已被注册');

            $tempPhone = Db::name('temp_phone')->where('phone', $tel)->order('id', 'desc')->find();
            if (empty($tempPhone)) {
                return returnJson(0, '请先获取验证码');
            }
            if ($tempPhone['code'] != $phone_code || (time() > $tempPhone['deadline'])) {
                return returnJson(0, '手机验证码不正确');
            }
            $result = MerchantModel::regist($tel, $pw);
            if ($result) {
                $merchant = MerchantModel::getMerchant($tel);
                cookie('phone', $merchant['merchant_tel'], time() + 3 * 3600);
                session('merchant', $merchant);
                return returnJson(1, '注册成功！');
            } else {
                return returnJson(0, $result);
            }
        } else {
            return returnJson(0, '请使用正确的方式提交数据');
        }
    }

    //判断手机是否已经注册
    public function isRegister()
    {
        $phone = input('param.phone');
        $hasMobile = MerchantModel::getMerchant($phone);
        if ($hasMobile)
            return returnJson(0, '该手机号已被注册');
        return returnJson(1, '该手机号未注册');
    }

    //发送短信获取验证码
    public function sendMessage()
    {
        $phone = input('param.phone');
        if (!is_mobile($phone)) {
            return returnJson(2, '请输入正确手机号');
        }
        //检测验证码
        $res = $this->captcha->check(input('param.captcha'));
        if (!$res) {
            return returnJson(2, '图片验证码错误');
        }
        //通过手机号获取一分钟内发送过的短信
        $res = $this->tempPhone->checkSecondInByPhone($phone);
        if (!$res) {
            return returnJson(2, '一分钟后尝试');
        }
        //检测用户ip地址,每小时不超过10次
        $res = $this->tempPhone->checkIpNoMoreTen(getIP());
        if (!$res) {
            return returnJson(2, '你的ip受限,请一小时后尝试');
        }
        $tool = new Tools;
        $result = $tool->sendMsg($phone);
        if (!$result) {
            return returnJson(0, '发送失败，请稍后重试');
        }
        return returnJson(1, '发送成功');
    }

    // 找回密码
    public function forget()
    {
        return view('forget');
    }

    public function updatePwd()
    {
        if (request()->isAjax()) {
            $tel = input('tel');
            $pw = input('pw');
            $phone_code = input('param.code');
            $is_mobile = is_mobile($tel);
            if (!$is_mobile)
                return returnJson(0, '请输入正确手机号');
            $merchant = MerchantModel::getMerchant($tel);
            if (!$merchant)
                return returnJson(0, '该手机号未注册');

            $tempPhone = Db::name('temp_phone')->where('phone', $tel)->order('id', 'desc')->find();
            if (empty($tempPhone)) {
                return returnJson(0, '请先获取验证码');
            }
            if ($tempPhone['code'] != $phone_code || (time() > $tempPhone['deadline'])) {
                return returnJson(0, '验证码不正确');
            }
            $result = MerchantModel::updatePwd($tel, $pw);
            if ($result !== false) {
                return returnJson(1, '修改密码成功');
            } else {
                return returnJson(0, '修改密码失败，请稍后重试');
            }
        } else {
            return returnJson(0, '请使用正确的方式提交数据');
        }
    }

    /**
     * 激活
     */
    public function activeMerchantAccount()
    {
        if (MerchantModel::activeMerchantAccount()) {
            session('merchant.merchant_account_status', 1);
            return returnJson(1, '激活成功');
        }
        return returnJson(1, '激活失败');
    }

    public function loginOut()
    {
        cookie('phone', null);
        session('merchant', null);
        $this->redirect('/');
    }
}
